import getopt
import sys
import traceback
import time
import os
from ConfigParser import SafeConfigParser

from sqlalchemy import *
from sqlalchemy.orm import mapper
from sqlalchemy.orm import sessionmaker

from DataSchema import *
from Repository import *
from Util import *

class Doc4:

    
    def __init__(self):
        self.config = SafeConfigParser()
        self.config_file = "/etc/doc4.cfg"
        self.config.read(self.config_file)
        self.dbuser = self.config.get("database", "user")
        self.dbpasswd = self.config.get("database", "password")
        self.dbname = self.config.get("database", "name")
        self.dbhost = self.config.get("database", "host")
        self.extraction_dir = self.config.get("extraction", "outputdir")
        self.logpath = None
        #self.engine = MySQLdb.connect(self.dbhost, self.dbuser, self.dbpasswd, self.dbname)
        self.date_format = "%Y-%m-%d %H:%M:%S" 
        #self.distribs = eval(self.config.get("repositories", "distributions"))
        #self.providers = eval(self.config.get("repositories", "providers"))
        #self.architectures = eval(self.config.get("repositories", "architectures"))
        #self.branches = eval(self.config.get("repositories", "branches"))
        #self.sections = eval(self.config.get("repositories", "sections"))
        self.repository_ids = eval(self.config.get("repositories", "ids"))
        self.schema = DataSchema()
        self.engine = create_engine('mysql://%s:%s@%s/%s' % (self.dbuser, self.dbpasswd, self.dbhost, self.dbname), assert_unicode='warn')
        

    
    ##move to Util
    def string_to_integer(self, str):
         #SQL: floor(length(package) / ASCII(package) * 1000)
        length = len(str)
        code = ord(str[0])
        value = length * 1000 / code
        return value
        
        
    def initialize_database(self):
        self.load_mandriva_repositories()
        

    def get_repository(self, repository_id):
        Session = sessionmaker(bind=self.engine)
        session = Session()
        mapper(Repository, self.schema.repository_table)
        repository = session.query(Repository).filter_by(id_repository=repository_id).first()
        session.close()
        return repository


    #
    # Get the repositories of the given distribution matching the constraints expressed in doc4packages.cfg
    #
    def get_distribution_repositories(self, distrib):
        repo_query = self.config.get("rsync", "repository_query")
        repo_query = repo_query % (distrib, concat(self.providers), concat(self.architectures), concat(self.branches), concat(self.sections))
        connection = self.engine.connect()
        repositories = []
        repos = connection.execute(repo_query)
        print repo_query
        for repo in repos:
            #repository_query = select distribution,provider,URL,port,username,password,architecture,branch,section from REPOSITORIES
            repository = Repository(repo[0], repo[1], repo[2], repo[3], repo[4], repo[5], repo[6], repo[7], repo[8], repo[9])
            repositories.append(repository)
        connection.close()
        return repositories

            
    def log(self, message, level=0):
    #    def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")
    #    message = sdf.format(new Date())+" "+message
        if (level == 0):
            logm = "INFO"
        elif (level == 1):
            logm = "WARN"
        elif (level == 2):
            logm = "ERROR"
        
        now = time.strftime(self.date_format)
        print "[%s] %s - %s" % (logm, now, message)
#        if not os.path.exists(self.logpath):
#            try:
#                os.makedirs(self.logpath)
#            except Exception, e:
#                traceback.print_exc(file=sys.stdout)
#                sys.exit(0)

        logfile = open(self.logpath, 'a+')
        logfile.write("[%s] %s - %s\n" % (logm, now, message))
        logfile.close()
        
    def set_package_state(self, pkg, action, dateField, state, error):
        now = time.strftime(self.date_format)      
        error = error.replace("'", "\\'")
        query = "update d4_queue SET action_state='%s', %s='%s', error_message='%s' where file='%s' and action='%s'" % (state, dateField, now, error, pkg, action)
        resut = self.execute_sql(query)

    def execute_sql(self, query, params=None):
        connection = self.engine.connect()
        result = connection.execute(query, params=None)
        connection.close()
        return result


def sqlencode(str):
    if str is None:
        return ""
    return str.replace("'", "\\'")

def concat(list):
    if list == None:
        return ""
    else:
        s = str()
        for elt in list:
            s = s + "'" + elt + "',"
        return s[0:len(s) - 1]

    
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "")
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    if len(args) < 0:
        usage()

    doc4 = Doc4()

    for arg in args:
        if arg in ["start", "stop", "status"]:
            try:
                doc4 = Doc4()
#                repos =  doc4.get_distribution_repositories("cooker")
#                for repo in repos:
#                    print repo
#                

                #eval("pacx.%s()" % arg)
            except KeyboardInterrupt:
                sys.exit(0)
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
                sys.exit(0)
        else:
            usage()

def usage():
    usage = "Doc4 start|stop|status"
    print usage

        
if __name__ == "__main__":
    main()


#pacx = Pacx()
#print pacx.string_to_integer("olena-1.0-1mdv2010.0.src.rpm")
